package com.qyhl.party.party;

import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.party.R;
import com.qyhl.party.R2;
import com.qyhl.party.party.study.PartyStudyFragment;
import com.qyhl.party.party.test.PartyTestFragment;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.party.PartyLoginBean;
import com.qyhl.webtv.commonlib.entity.party.PartyUserInfo;
import com.qyhl.webtv.commonlib.service.CircleService;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.weavey.loading.lib.LoadingLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Route(path = ARouterPathConstant.PARTY_BUILDING_HOME, extras = ARouterPathConstant.LOGIN_NEEDED)
public class PartyHomeActivity extends BaseActivity implements PartyHomeContract.PartyHomeView {
    @BindView(R2.id.bottom_view)
    BottomNavigationView bottomView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = ServicePathConstant.CIRCLE_SERVICE)
    public CircleService circleService;

    @Autowired(name = "position")
    int position = 0;

    PartyLoginBean mBean;

    private int lastIndex;
    private List<Fragment> mFragments;
    private PartyHomePresenter mPresenter;

    private final int[] ids = new int[]{R.id.study, R.id.test, R.id.community};

    @Override
    protected int getContentView() {
        return R.layout.party_activity_home;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new PartyHomePresenter(this);

        mPresenter.isLogin();
    }

    @Override
    protected void setListener() {
        bottomView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.study) {
                    setFragmentPosition(0);
                } else if (itemId == R.id.test) {
                    setFragmentPosition(1);
                } else if (itemId == R.id.community) {
                    setFragmentPosition(2);
                }
                // 这里注意返回true,否则点击失效
                return true;
            }
        });


        //取消长按Toast
        View menuView = bottomView.getChildAt(0);
        for (int id : ids) {
            menuView.findViewById(id).setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });
        }

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.isLogin();
            }
        });
    }

    private void setFragmentPosition(int position) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = mFragments.get(position);
        Fragment lastFragment = mFragments.get(lastIndex);
        lastIndex = position;
        ft.hide(lastFragment);
        if (!currentFragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
            ft.add(R.id.frameLayout, currentFragment);
        }
        ft.show(currentFragment);
        ft.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void LoginSuccess(PartyLoginBean bean) {
        mBean = bean;
        mPresenter.getUserInfo(bean.getAuthorization());
    }

    @Override
    public void LoginError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        if (StringUtils.isNotEmpty(msg) && msg.equals("请补充资料！")) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.PARTY_SUPPLEMENT)
                    .withBoolean("isEdit", false)
                    .navigation(this, new NavCallback() {
                        @Override
                        public void onArrival(Postcard postcard) {
                            finish();
                        }
                    });
            showToast(msg);
        } else {
            loadMask.setErrorText(msg);
            loadMask.setStatus(LoadingLayout.Error);
        }

    }

    @Override
    public void setInfo(PartyUserInfo bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        mFragments = new ArrayList<>();
        mFragments.add(PartyStudyFragment.newInstance(mBean.getAuthorization(), bean.getIntegral()));
        mFragments.add(PartyTestFragment.newInstance(mBean.getAuthorization(), mBean.getUserInfo().getName(), bean.getBestPassCount(), bean.getPkWrongCount(), bean.getPkCorrectCount()));
        Fragment cFragment = circleService.getPartyCircleFragment("408");
        mFragments.add(cFragment);
        // 初始化展示MessageFragment
        bottomView.getMenu().getItem(position).setChecked(true);
        if (position != 0) {
            setFragmentPosition(0);
        }
        setFragmentPosition(position);

    }

    @Override
    public void setError(String msg) {
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
    }

    public void doFinish() {
        finish();
    }
}
